/*
 * Copyright 2013 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.aplink.generic.autosync;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SyncStatusObserver;
import android.os.Bundle;

import com.aplink.generic.controller.GenericApplication;
import com.aplink.generic.pojo.MasterConfig;
import com.aplink.generic.sharepreference.GenericSharePreference;

public class SyncUtils {
    private static SyncUtils sInstance = null;

    public static SyncUtils getInstance() {
        if (SyncUtils.sInstance == null) {
            SyncUtils.sInstance = new SyncUtils();
            SyncUtils.sInstance.mMasterConfig = GenericApplication
                    .getInstance().getMasterConfig();
            if (SyncUtils.sInstance.mMasterConfig.getAutoSync() != null) {
                SyncUtils.sInstance.mAuthority = SyncUtils.sInstance.mMasterConfig
                        .getAutoSync().getAuthorities();
            }
        }
        return SyncUtils.sInstance;
    }

    private String mAuthority = null;
    private MasterConfig mMasterConfig;

    private Object mSyncObserverHandle;

    private final SyncStatusObserver mSyncStatusObserver = new SyncStatusObserver() {

        @Override
        public void onStatusChanged(final int which) {

        }
    };

    public void CreateSyncAccount() {
        if (this.mMasterConfig.getAutoSync() != null) {
            boolean newAccount = false;
            final Context context = GenericApplication.getInstance()
                    .getApplicationContext();
            final boolean setupComplete = GenericSharePreference.getInstance()
                    .isSetUpAccountComplete();
            final Account account = GenericAccountService
                    .GetAccount(this.mMasterConfig);
            final AccountManager accountManager = (AccountManager) context
                    .getSystemService(Context.ACCOUNT_SERVICE);
            if (accountManager.addAccountExplicitly(account, null, null)) {
                ContentResolver.setIsSyncable(account, this.mAuthority, 1);
                ContentResolver.addPeriodicSync(account, this.mAuthority,
                        new Bundle(), this.mMasterConfig.getAutoSync()
                                .getInterval());
                newAccount = true;
            }
            if (newAccount || !setupComplete) {
                GenericSharePreference.getInstance().setUpAccountComplete(true);
            }
        }
    }

    public void disableAutoSync() {
        if (GenericSharePreference.getInstance().isSetUpAccountComplete()) {
            stopSync();
            if (this.mSyncObserverHandle != null) {
                ContentResolver
                        .removeStatusChangeListener(this.mSyncObserverHandle);
                this.mSyncObserverHandle = null;
            }
        }
    }

    public void enableAutoSync() {
        final Account account = GenericAccountService
                .GetAccount(this.mMasterConfig);
        ContentResolver.setSyncAutomatically(account, this.mAuthority, true);
        this.mSyncStatusObserver.onStatusChanged(0);
        final int mask = ContentResolver.SYNC_OBSERVER_TYPE_PENDING
                | ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE;
        this.mSyncObserverHandle = ContentResolver.addStatusChangeListener(
                mask, this.mSyncStatusObserver);
    }

    public void stopSync() {
        final Account account = GenericAccountService
                .GetAccount(this.mMasterConfig);
        ContentResolver.setSyncAutomatically(account, this.mAuthority, false);
    }

    public void TriggerRefresh() {
        final Bundle b = new Bundle();
        b.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
        b.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
        ContentResolver.requestSync(
                GenericAccountService.GetAccount(this.mMasterConfig),
                this.mAuthority, b);
    }
}
